<?php
namespace Api\Controller;
use Think\Controller;
class ProductController extends BaseController{
  /**
  *获取某分类下的子分类 get
  *@param: categoryId
  *@return:
  */
  public function getProductCategory(){
    $categoryId = I('get.categoryId');
    if(!$categoryId){
      $this->response(array('info'=>'缺少分类id'),json,400);
    }
    $categories = M('product_category')
    ->where(array('parent_id'=>$categoryId))
    ->order('sort asc')
    ->select();
    $this->response(array('info'=>$categories),json,200);
  }

  /**
  *获取某分类下的商品 get
  *@param: categoryId
  *@return:
  */
  public function getProducts(){
    $categoryId = I('get.categoryId');
    if($categoryId){
      $map['category_id'] = $categoryId;
    }
    $keyword = I('get.keyword');
    if($keyword){
      $map['_string'] = 'name like "%'.$keyword.'%" or name_en like "%'.$keyword.'%"';
    }
    $map['product.status'] = 1;
    $products = M('product')
    ->field('product.*,picture.path as cover_paths')
    ->where($map)
    ->join('picture on picture.id = cover','left')
    ->select();

    foreach ($products as $product_key => $product) {
      $new_banner = array();
      //转化banner
      if($product['banner']){
        $products[$product_key]['banner'] = explode(',',$product['banner']);
        foreach ($products[$product_key]['banner'] as $key => $value) {
          # code...
          $re_pic = M('picture')->where(array('id'=>$value))->find();
          if($re_pic){
            array_push($new_banner,$re_pic['path']);
          }
        }
        $products[$product_key]['banner'] = $new_banner;
      }
      //查找价格
      $attr = M('product_attribution')
      ->where(array('product_id'=>$product['id'],'is_deleted'=>0))
      ->order('price asc')
      ->select();
      $len = count($attr);
      if($len==1){
        $products[$product_key]['price_low'] = $attr[0]['price'];
        $products[$product_key]['price_high'] = $attr[0]['price'];
      }
      if($len>1){
        $products[$product_key]['price_low'] = $attr[0]['price'];
        $products[$product_key]['price_high'] = $attr[$len-1]['price'];
      }
    }
    $this->response(array('info'=>$products),json,200);
  }

  /**
  *获取商品详情 get
  *@param: productId
  *@return:
  */
  public function getProduct(){
    $productId = I('get.productId');
    if(!$productId){
      $this->response(array('info'=>'缺少商品id'),json,400);
    }
    $product = M('product')
    ->field('product.*,picture.path as cover_paths')
    ->where(array('product.id'=>$productId,'product.status'=>1))
    ->join('picture on picture.id = cover','left')
    ->find();

    $new_banner = array();
    if($product['banner']){
      $product['banner'] = explode(',',$product['banner']);
      foreach ($product['banner'] as $key => $value) {
        # code...
        $re_pic = M('picture')->where(array('id'=>$value))->find();
        if($re_pic){
          array_push($new_banner,$re_pic['path']);
        }
      }
      $product['banner'] = $new_banner;
    }

    $attr = M('product_attribution')
    ->where(array('product_id'=>$productId,'is_deleted'=>0))
    ->select();

    $product['attributions'] = $attr;
    $this->response(array('info'=>$product),json,200);
  }

  /**
  *加入购物车 post
  *@param: attributionId,quantity
  *@return:
  */
  public function addToCart(){
    $uid = $this->securityTest();
    $post = json_decode(file_get_contents('php://input'), true);
    // $post = I('post.');
    if(!$post['attributionId']){
      $this->response(array('info'=>'参数错误'),json,400);
    }
    if(!$post['quantity']||$post['quantity']<=0){
      $this->response(array('info'=>'请选择至少一张票进行购买'),json,400);
    }

    //检测是否已有该商品在购物车,且未下单
    $re_cart = M('cart')->where(array('visitor_id'=>$uid,'attribution_id'=>$post['attributionId'],'status'=>1))->find();
    if($re_cart){
      $re = M('cart')->where(array('visitor_id'=>$uid,'attribution_id'=>$post['attributionId']))->save(array('date_added'=>time(),'quantity'=>$re_cart['quantity']+$post['quantity']));
      $this->response(array('info'=>'加入成功'),json,200);
    }

    //查询该属性价格
    $re_attr = M('product_attribution')->find($post['attributionId']);

    $data['visitor_id'] = $uid;
    $data['product_id'] = $re_attr['product_id'];
    $data['attribution_id'] = $post['attributionId'];
    $data['quantity'] = $post['quantity'];
    $data['date_added'] = time();
    $data['price'] = $re_attr['price'];
    $data['activity_price'] = $re_attr['activity_price'];

    if(M('cart')->add($data)){
      $this->response(array('info'=>'加入成功'),json,200);
    }
  }

  /**
  *购物车某商品数量修改 post
  *@param: cartId,quantity
  *@return:
  */
  public function saveToCart(){
    $uid = $this->securityTest();
    $post = json_decode(file_get_contents('php://input'), true);
    if(!$post['cartId']){
      $this->response(array('info'=>'参数错误'),json,400);
    }
    if($post['quantity']<0){
      $this->response(array('info'=>'不可为负数'),json,400);
    }
    $re = M('cart')->where(array('id'=>$post['cartId']))->save($post);
    if($re){
      $this->response(array('info'=>'修改成功'),json,200);
    }
  }

  /**
  *我的购物车 get
  *@param: 
  *@return:
  */
  public function myCart(){
    $uid = $this->securityTest();
    $map['quantity'] = array('gt',0);
    $data = M('cart')
    ->field('cart.*,picture.path as product_cover,product.name as product_name,product.name_en as product_name_en,product_attribution.name as attr_name,product_attribution.name_en as attr_name_en')
    ->where(array('cart.visitor_id'=>$uid,'cart.status'=>1))
    ->where($map)
    ->join('product on product.id = cart.product_id')
    ->join('product_attribution on product_attribution.id = cart.attribution_id')
    ->join('picture on picture.id = product.cover','left')
    ->select();

    $this->response(array('info'=>$data),json,200);
  }

  /**
  *获取省市县 get
  *@param: pid(上一级的id，若请求省，不需要传)
  *@return:
  */
  public function getCities(){
    $pid = I('get.pid')?I('get.pid'):0;
    $cities = M('region')->where(array('pid'=>$pid))->select();

    $this->response(array('info'=>$cities),json,200);
  }

  /**
  *新增地址 post
  *@param: name,phone,province省,city市,district县/区,area详细地址
  *@return:
  */
  public function addAddress(){
    $uid = $this->securityTest();
    $post = json_decode(file_get_contents('php://input'), true);
    // $post = I('post.');
    if(!$post['name']){
      $this->response(array('info'=>'请输入收件人姓名'),json,400);
    }
    if(!$post['phone']){
      $this->response(array('info'=>'请输入收件人联系方式'),json,400);
    }
    if(!$post['province']||!$post['city']||!$post['district']||!$post['area']){
      $this->response(array('info'=>'请输入地址'),json,400);
    }
    $post['visitor_id'] = $uid;
    //若设置了默认地址，将其他置位0
    if($post['is_default']==1){
      $myaddress = M('address')
      ->where(array('visitor_id'=>$uid))
      ->select();
      foreach ($myaddress as $key => $value) {
        # code...
        if($value['is_default']==1){
          M('address')->where(array('id'=>$value['id']))->save(array('is_default'=>0));
        }
      }
    }

    if(M('address')->add($post)){
      $this->response(array('info'=>'添加成功！'),json,200);
    }
  }

  /**
  *修改地址 post
  *@param: addressId,name,phone,province省,city市,district县/区,area详细地址
  *@return:
  */
  public function editAddress(){
    $uid = $this->securityTest();
    $post = json_decode(file_get_contents('php://input'), true);
    // $post = I('post.');
    if(!$post['addressId']){
      $this->response(array('info'=>'请输入地址id'),json,400);
    }
    if(!$post['name']){
      $this->response(array('info'=>'请输入收件人姓名'),json,400);
    }
    if(!$post['phone']){
      $this->response(array('info'=>'请输入收件人联系方式'),json,400);
    }
    if(!$post['province']||!$post['city']||!$post['district']||!$post['area']){
      $this->response(array('info'=>'请输入地址'),json,400);
    }
    //若设置了默认地址，将其他置位0
    if($post['is_default']==1){
      $myaddress = M('address')
      ->where(array('visitor_id'=>$uid))
      ->select();
      foreach ($myaddress as $key => $value) {
        # code...
        if($value['is_default']==1){
          M('address')->where(array('id'=>$value['id']))->save(array('is_default'=>0));
        }
      }
    }
    M('address')->where(array('id'=>$post['addressId']))->save($post);
    $this->response(array('info'=>'修改成功！'),json,200);
  }

  /**
  *删除地址 post
  *@param: addressId
  *@return:
  */
  public function deleteAddress(){
    $uid = $this->securityTest();
    $post = json_decode(file_get_contents('php://input'), true);
    // $post = I('post.');
    if(!$post['addressId']){
      $this->response(array('info'=>'请输入地址id'),json,400);
    }
    M('address')->where(array('id'=>$post['addressId']))->save(array('is_deleted'=>1));
    $this->response(array('info'=>'删除成功！'),json,200);
  }

  /**
  *我的地址 get
  *@param: 
  *@return:
  */
  public function myAddresses(){
    $uid = $this->securityTest();
    $data = M('address')
    ->field('address.*,r1.name as province_name,r2.name as city_name,r3.name as district_name')
    ->where(array('address.visitor_id'=>$uid,'address.is_deleted'=>0))
    ->join('region r1 on r1.id = province','left')
    ->join('region r2 on r2.id = city','left')
    ->join('region r3 on r3.id = district','left')
    ->select();

    $this->response(array('info'=>$data),json,200);
  }

  /**
  *某条地址详情 get
  *@param: addressId
  *@return:
  */
  public function addressDetail(){
    $uid = $this->securityTest();
    $addressId = I('get.addressId');
    if(!$addressId){
      $this->response(array('info'=>'参数错误'),json,200);
    }
    $data = M('address')
    ->field('address.*,r1.name as province_name,r2.name as city_name,r3.name as district_name')
    ->where(array('address.id'=>$addressId))
    ->join('region r1 on r1.id = province','left')
    ->join('region r2 on r2.id = city','left')
    ->join('region r3 on r3.id = district','left')
    ->find();

    $this->response(array('info'=>$data),json,200);
  }

  /**
  *购物车下单 post
  *@param: 
  *@return:
  */
  public function confirmProductOrder(){
    $uid = $this->securityTest();
    $post = json_decode(file_get_contents('php://input'), true);
    // $post = I('post.');
    //查找购物车所有未下单且数量不为0条目 1:已加入 2:已下单
    $map['quantity'] = array('gt',0);
    $carts = M('cart')
    ->where(array('visitor_id'=>$uid,'status'=>1))
    ->where($map)
    ->select();

    if(count($carts)<=0){
      $this->response(array('info'=>'没有可结算的商品'),json,400);
    }
    
    $cart_ids = array();//拼成id字符串
    $total = 0;//总金额
    foreach ($carts as $key => $value) {
      if($value['activity_price']>0){
        $total = $total + $value['activity_price'] * $value['quantity'];
      }else{
        $total = $total + $value['price'] * $value['quantity'];
      }
      array_push($cart_ids,$value['id']);
    }
    $cart_ids = implode(',',$cart_ids);

    $data['visitor_id'] = $uid;
    $data['cart_ids'] = $cart_ids;
    $data['total'] = $total;
    $data['create_time'] = time();
    $data['payment'] = 1;//暂时为1微信支付
    $data['express_co'] = '顺丰到付';//暂时均为顺丰到付

    $re_order = M('product_order')->add($data);
    if($re_order){
      $date = date("Ymd");
      // 更新订单号
      M('product_order')->where(array('id'=>$re_order))->save(array('order_num'=>'P'.$date.$re_order));
      //cart中所有条目状态置为2，并且添加产品-订单对应表
      foreach ($carts as $key => $value) {
        # code...
        M('cart')->where(array('id'=>$value['id']))->save(array('status'=>2));
        //添加产品-订单对应表
        $order_product['create_time'] = time();
        $order_product['product_order_id'] = $re_order;
        $order_product['cart_id'] = $value['id'];
        $order_product['visitor_id'] = $value['visitor_id'];
        $order_product['product_id'] = $value['product_id'];
        $order_product['attribution_id'] = $value['attribution_id'];
        $order_product['quantity'] = $value['quantity'];
        M('product_to_cart')->add($order_product);
      }
      $this->response(array('info'=>$re_order),json,200);
    }else{
      $this->response(array('info'=>'下单失败'),json,400);
    }
  }

  /**
  *结算页面获取订单详情 get
  *@param: orderId
  *@return:
  */
  public function productOrderDetail(){
    $uid = $this->securityTest();
    $orderId = I('get.orderId');
    if(!$orderId){
      $this->response(array('info'=>'参数错误'),json,200);
    }
    $data = M('product_order')
    ->field('product_order.*,address.province,address.name as address_name,address.phone as address_phone,r1.name as province_name,r2.name as city_name,r3.name as district_name,address.area,visitor.name')
    ->join('visitor on visitor.id = product_order.visitor_id','left')
    ->join('address on address.id = product_order.address_id','left')
    ->join('region r1 on r1.id = address.province','left')
    ->join('region r2 on r2.id = address.city','left')
    ->join('region r3 on r3.id = address.district','left')
    ->where(array('product_order.id'=>$orderId))
    ->find();

    //查询cart信息
    if(strlen($data['cart_ids'])>0){
      $ids = explode(',',$data['cart_ids']);
      $products = array();
      foreach ($ids as $key => $value) {
        $product = M('cart')
        ->field('cart.*,picture.path as product_cover,product.name as product_name,product.name_en as product_name_en,product_attribution.name as attr_name,product_attribution.name_en as attr_name_en')
        ->where(array('cart.id'=>$value))
        ->join('product on product.id = cart.product_id')
        ->join('product_attribution on product_attribution.id = cart.attribution_id')
        ->join('picture on picture.id = product.cover','left')
        ->find();
        array_push($products,$product);
      }
      $data['products'] = $products;
    }

    //查询默认地址
    $data['default_address']=M('address')
    ->field('address.*,r1.name as province_name,r2.name as city_name,r3.name as district_name')
    ->where(array('visitor_id'=>$uid,'is_default'=>1))
    ->join('region r1 on r1.id = address.province','left')
    ->join('region r2 on r2.id = address.city','left')
    ->join('region r3 on r3.id = address.district','left')
    ->find();

    $this->response(array('info'=>$data),json,200);
  }

  /**
  *取消订单 post
  *@param: orderId
  *@return:
  */
  public function cancelOrder(){
    $uid = $this->securityTest();
    $post = json_decode(file_get_contents('php://input'), true);
    // $post = I('post.');
    if(!$post['orderId']){
      $this->response(array('info'=>'参数错误'),json,400);
    }
    $re_order = M('product_order')->find($post['orderId']);
    if($re_order['status']!='0'){
      $this->response(array('info'=>'该订单不可取消，请联系售后人员'),json,400);
    }
    M('product_order')->where(array('id'=>$post['orderId']))->save(array('status'=>6));
    $this->response(array('info'=>'已取消'),json,200);
  }

  /**
  *product_to_cart 初始化
  *@param: 
  *@return:
  */
  public function productToCartInit(){
    $orders = M('product_order')->select();
    foreach ($orders as $key_order=>$order) {
      $carts = M('cart')->where(array('id'=>array('in',$order['cart_ids'])))->select();
      foreach ($carts as $key_cart=>$cart) {
        $product_to_cart['product_order_id'] = $order['id'];
        $product_to_cart['cart_id'] = $cart['id'];
        $product_to_cart['visitor_id'] = $order['visitor_id'];
        $product_to_cart['product_id'] = $cart['product_id'];
        $product_to_cart['attribution_id'] = $cart['attribution_id'];
        $product_to_cart['quantity'] = $cart['quantity'];
        $product_to_cart['create_time'] = $order['create_time'];
        M('product_to_cart')->add($product_to_cart);
      }
    }
  }

}